package com.example.demo;

import java.sql.*;
import java.util.Random;

/**
 * @author sk.z
 */
public class TableMessage {

    TableMessage() {
        try {
            Statement statement = MysqlConnection.get().createStatement();
            statement.executeQuery("use hh");
            statement.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public void showCreateTable() {
        try {
            Statement statement = MysqlConnection.get().createStatement();
            ResultSet resultSet = statement.executeQuery("SHOW CREATE TABLE message");
            resultSet.next();
            System.out.println(resultSet.getString("Create Table"));
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void insert() {
        try {
            PreparedStatement preparedStatement = MysqlConnection.get().prepareStatement("INSERT INTO message(user_id, title, content, create_time) VALUES(?,?,?,?)");
            Random random = new Random();
            for (int row = 0; row < 5; row++) {
                String s = random.nextInt(99999) + "";
                preparedStatement.setString(1, "10001");
                preparedStatement.setString(2, s);
                preparedStatement.setString(3, s);
                preparedStatement.setDate(4, new Date(System.currentTimeMillis()));
                preparedStatement.addBatch();
            }
            preparedStatement.executeBatch();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public void select() {
        try {
            Statement statement = MysqlConnection.get().createStatement();
            ResultSet resultSet = statement.executeQuery("SELECT * FROM message order by mes_id desc limit 10");
            while (resultSet.next()) {
                System.out.print(resultSet.getLong(1) + "\t");
                System.out.print(resultSet.getString(2) + "\t");
                System.out.print(resultSet.getString(3) + "\t");
                System.out.print(resultSet.getString(4) + "\t");
                System.out.print(resultSet.getString(5));
                System.out.println();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
